package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.aliyun.tea.utils.StringUtils;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentType;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class CommentsService {
    @DubboReference
    private CommentApi commentApi;
    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 发布评论
     * @param movementId id
     * @param content 内容
     */
    public void saveComments(String movementId, String content) {
        //1、获取操作用户id
        Long userId = UserHolder.getUserId();
        //构造Comment
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.COMMENT.getType());
        comment.setContent(content);
        comment.setUserId(userId);
        comment.setCreated(System.currentTimeMillis());
        //往数据库保存评论
        commentApi.saveComment(comment);

        //更新动态评论数
    }

    /**
     * 分页查询评论列表
     * @param movementId 动态id
     * @param page 当前页
     * @param pagesize 记录数
     * @return
     */
    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        //1、调用API查询评论列表
        List<Comment> comments = commentApi.findComments(movementId, CommentType.COMMENT,page,pagesize);

        //2、判断list集合是否存在
        if (CollUtil.isEmpty(comments) || comments.size() <= 0){
            return new PageResult();
        }

        //3、提取所有的用户id,调用UserInfoAPI查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(comments, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //4、构造vo对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : comments) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }
        }
        //5、构造返回值
        return new PageResult(page,pagesize,100l,vos);

    }
}
